package com.yunzhou.controller.user;

import com.yunzhou.constants.RedisConstants;
import com.yunzhou.dto.DoCommentLikeDTO;
import com.yunzhou.dto.ForumCommentDTO;
import com.yunzhou.dto.PostForumCommentDTO;
import com.yunzhou.dto.UpdateCommentTopTypeDTO;
import com.yunzhou.entity.ForumComment;
import com.yunzhou.properties.JwtProperties;
import com.yunzhou.result.Result;
import com.yunzhou.service.ForumCommentService;
import com.yunzhou.service.UserService;
import com.yunzhou.utils.JwtUtil;
import com.yunzhou.utils.ThreadLocalUtil;
import com.yunzhou.vo.ForumCommentVO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/user/forumComment")
public class ForumCommentController {

    @Autowired
    private ForumCommentService forumCommentService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    // 获取文章对应评论   orderType排序类型 0:根据火热程度倒序排 1:根据时间倒序排
    @GetMapping("/getForumCommentList")
    public Result getComment(HttpServletRequest request, ForumCommentDTO forumCommentDTO){
        ForumCommentVO forumCommentVO = new ForumCommentVO();

        // 看用户是否登录
        String token = request.getHeader(jwtProperties.getTokenName());
        if (token == null) {
            // 当前用户未登录
            return Result.success(forumCommentService.getForumCommentList(forumCommentDTO.getArticleId(),
                    forumCommentDTO.getOrderType(), null ,forumCommentDTO.getPageNum(), forumCommentDTO.getPageSize()));
        }

        // 走到这里说明用户携带了Token，不过还要判断Token是否过期，去Redis中找Token
        String tokenKey = RedisConstants.LOGIN_TOKEN_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        if (userMap.isEmpty()) {
            // 没有通过token找到Redis中数据，说明Token已过期
            return Result.success(forumCommentService.getForumCommentList(forumCommentDTO.getArticleId(),
                    forumCommentDTO.getOrderType(), null ,forumCommentDTO.getPageNum(), forumCommentDTO.getPageSize()));
        }

        // 走到这里说明用户Token携带了并且没有过期，则获取Token中的UserId
        // 获取Token中存储的用户信息
        // Map<String, Object> claims = JwtUtil.parseToken(jwtProperties.getSecretKey(),token);
        // Long userId = Long.valueOf(claims.get("userId").toString());
        Long userId = Long.parseLong(stringRedisTemplate.opsForHash().get(tokenKey, "userId").toString());

        if (userService.selectByUserId(userId) == null) {
            // 当前用户未登录
            return Result.success(forumCommentService.getForumCommentList(forumCommentDTO.getArticleId(),
                    forumCommentDTO.getOrderType(), null ,forumCommentDTO.getPageNum(), forumCommentDTO.getPageSize()));
        }

        System.out.println("查询文章详情的当前登录的用户ID为：" + userId);

        // 可以添加判断：若管理员关闭了当前文章的评论功能，则不返回评论
        return Result.success(forumCommentService.getForumCommentList(forumCommentDTO.getArticleId(),
                forumCommentDTO.getOrderType(), userId ,forumCommentDTO.getPageNum(), forumCommentDTO.getPageSize()));
    }

    // 发表评论
    @PostMapping("/postForumComment")
    public Result postComment(PostForumCommentDTO postForumCommentDTO) throws Exception {
        System.out.println("前端传递过来的发表评论参数为：" + postForumCommentDTO);

        ForumComment forumComment = new ForumComment();
        forumComment.setParentCommentId(postForumCommentDTO.getParentCommentId());
        forumComment.setArticleId(postForumCommentDTO.getArticleId());
        forumComment.setArticleTitle(postForumCommentDTO.getArticleTitle());
        forumComment.setContent(postForumCommentDTO.getContent());
        forumComment.setReplyUserId(postForumCommentDTO.getReplyUserId());
        forumComment.setReplyNickname(postForumCommentDTO.getReplyNickname());
        forumComment = forumCommentService.postComment(forumComment, postForumCommentDTO.getCommentImg());
        return Result.success(forumComment);
    }

    // 评论点赞/取消评论点赞
    @PostMapping("/doCommentLike")
    public Result doCommentLike(@RequestBody DoCommentLikeDTO doCommentLikeDTO){
        return Result.success(forumCommentService.doCommentLike(doCommentLikeDTO.getCommentId()));
    }

    // 评论置顶/取消置顶
    @PostMapping("/changeCommentTopType")
    public Result changeCommentTopType(@RequestBody UpdateCommentTopTypeDTO updateCommentTopTypeDTO) {
        ForumComment forumComment = forumCommentService.getForumCommentByForumCommentId(
                updateCommentTopTypeDTO.getCommentId());
        if (!Objects.equals(forumComment.getUserId(), ThreadLocalUtil.getCurrentUserId())){
            throw new RuntimeException("非文章作者无法对评论进行置顶操作");
        }
        forumCommentService.updateForumCommentTopTypeByCommentId(updateCommentTopTypeDTO.getCommentId());
        return Result.success();
    }

    // 获取“我的文章评论列表”（其他人评论我，接收人是我）
    @GetMapping("/getMyForumCommentList")
    public Result getMyForumCommentList(ForumCommentDTO forumCommentDTO){
        ForumCommentVO forumCommentVO = new ForumCommentVO();
        forumCommentVO.setForumCommentList(
                forumCommentService.getForumCommentListByReplyUserId(
                        forumCommentDTO.getReplyUserId(),
                        forumCommentDTO.getOrderType(),
                        forumCommentDTO.getPageNum(),
                        forumCommentDTO.getPageSize()));
        forumCommentVO.setTotal(
                forumCommentService.getForumCommentListTotalByReplyUserId(
                        forumCommentDTO.getReplyUserId()));
        return Result.success(forumCommentVO);
    }

    // 获取“我发表的文章评论”（我评论其他人，发表人是我）
    @GetMapping("/getMyPostForumCommentList")
    public Result getMyPostForumCommentList(ForumCommentDTO forumCommentDTO){
        ForumCommentVO forumCommentVO = new ForumCommentVO();
        forumCommentVO.setForumCommentList(
                forumCommentService.getForumCommentListByUserId(
                        forumCommentDTO.getUserId(),
                        forumCommentDTO.getOrderType(),
                        forumCommentDTO.getPageNum(),
                        forumCommentDTO.getPageSize()));
        forumCommentVO.setTotal(
                forumCommentService.getForumCommentListTotalByUserId(
                        forumCommentDTO.getUserId()));
        return Result.success(forumCommentVO);
    }

    // 根据评论ID删除评论（只有自己文章的评论才能删除）
    @DeleteMapping("/deleteForumCommentByCommentId")
    public Result deleteForumCommentByCommentId(ForumCommentDTO forumCommentDTO){
        System.out.println("删除评论参数"+forumCommentDTO);
        forumCommentService.deleteForumCommentByCommentId(forumCommentDTO.getCommentId());
        return Result.success();
    }

}
